import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, message, Space, Typography, Spin } from 'antd';
import request from '@/utils/request';
import dayjs from 'dayjs';
import DraggableTable from '@/components/DraggableTable';
import type { TableProps } from 'antd/es/table';

const { Title, Text } = Typography;

const statusMap: Record<number, string> = {
  1: '发布成功',
  0: '发布失败',
  2: '待发布',
  3: '发布中'
};
const statusColor: Record<number, string> = {
  1: 'green',
  0: 'red',
  2: 'orange',
  3: 'blue'
};

const ReleaseDetail: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [info, setInfo] = useState<any>(null);
  const [files, setFiles] = useState<any[]>([]);
  const [bpLoading, setBpLoading] = useState(false);
  const [columns, setColumns] = useState<TableProps<any>['columns']>([
    { title: '序号', dataIndex: 'index', key: 'index', width: 60, render: (_: any, __: any, idx: number) => idx + 1 },
    { title: '文件名', dataIndex: 'file_name', key: 'file_name', width: 200, ellipsis: true },
    { title: '文件路径', dataIndex: 'file_path', key: 'file_path', width: 200, ellipsis: true },
    { title: '数据大小(MB)', dataIndex: 'data_size', key: 'data_size', width: 120, render: (v: number) => (v / 1024 / 1024).toFixed(2) },
    { title: '任务型号', dataIndex: 'task_type', key: 'task_type', width: 100 },
    { title: '接收站', dataIndex: 'station', key: 'station', width: 100 },
    { title: '载荷', dataIndex: 'dm_zhname', key: 'dm_zhname', width: 100 },
    { title: '版本号', dataIndex: 'version_num', key: 'version_num', width: 100 },
    { title: '数据等级', dataIndex: 'data_level', key: 'data_level', width: 100 },
    { title: '数据发布时间', dataIndex: 'release_time', key: 'release_time', width: 160 },
    {
      title: '发布状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (v: number) => <span style={{ color: statusColor[v] }}>{statusMap[v] || '-'}</span>
    },
    { title: '失败原因', dataIndex: 'error_message', key: 'error_message', width: 120 }
  ]);

  useEffect(() => {
    if (!id) return;
    setLoading(true);
    request
      .get('/Management/DataListReleaseDetail', { params: { release_task_id: id } })
      .then((res) => {
        if (res.status === 200 && res.data.data) {
          setInfo(res.data.data.introduce);
          setFiles(res.data.data.files || []);
        }
      })
      .catch((e) => {
        message.error(e?.message || '获取详情失败');
      })
      .finally(() => setLoading(false));
  }, [id]);

  // 断点续推
  const handleBreakpoint = async () => {
    setBpLoading(true);
    try {
      const res = await request.post('/Management/DataReleaseBreakpointContinuation', {
        release_task_ids: [id]
      });
      if (res.status === 200) {
        message.success('断点续推已发起');
        // 可选：刷新数据
        // fetchDetail();
      } else {
        message.error(res.data?.msg || '断点续推失败');
      }
    } catch (e: any) {
      message.error(e?.message || '断点续推失败');
    } finally {
      setBpLoading(false);
    }
  };

  return (
    <div style={{ background: '#fff', padding: 24, minHeight: 600 }}>
      <Button onClick={() => navigate(-1)}>返回</Button>
      <Title level={4} style={{ textAlign: 'center', marginBottom: 0 }}>
        发布报告详情
      </Title>
      <div style={{ textAlign: 'right', padding: 16 }}>
        生成时间：{info?.generation_time ? dayjs(info.generation_time).format('YYYY-MM-DD HH:mm:ss') : '-'}
      </div>
      {loading ? (
        <Spin />
      ) : (
        <>
          {/* 汇总信息 */}
          <div style={{ background: '#f5f5f5', padding: 16, marginBottom: 24 }}>
            <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', marginBottom: 8 }}>
              <div style={{ flex: 1 }}>报告编号：{info?.report_no || '-'}</div>
              <div style={{ flex: 1, textAlign: 'center' }}>发布开始时间：{info?.release_start_time || '-'}</div>
              <div style={{ flex: 1, textAlign: 'right' }}>发布结束时间：{info?.release_end_time || '-'}</div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', marginBottom: 8 }}>
              <div style={{ flex: 1 }}>发布数据总量(MB)：{(info?.files_size / 1024 / 1024).toFixed(2) || '-'}</div>
              <div style={{ flex: 1, textAlign: 'center' }}>
                成功数据量(MB)：{(info?.release_success_size / 1024 / 1024).toFixed(2) || '-'}
              </div>
              <div style={{ flex: 1, textAlign: 'right' }}>失败数据量(MB)：{(info?.release_fail_size / 1024 / 1024).toFixed(2) || '-'}</div>
            </div>
            <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between' }}>
              <div style={{ flex: 1 }}>文件数：{info?.files_count || '-'}</div>
              <div style={{ flex: 1, textAlign: 'center' }}>成功文件数：{info?.release_success_count || '0'}</div>
              <div style={{ flex: 1, textAlign: 'right' }}>失败文件数：{info?.release_fail_count || '0'}</div>
            </div>
          </div>
          {/* 文件明细表格 */}
          <div style={{ marginBottom: 8 }}>
            共{files.length}条数据，成功{info?.release_success_count || 0}条，失败{info?.release_fail_count || 0}条
          </div>
          <DraggableTable
            rowKey="id"
            tableLayout="fixed"
            columns={columns}
            dataSource={files}
            size="small"
            bordered
            pagination={false}
            scroll={{ x: 'max-content', y: 400 }}
            onColumnsChange={(columns) => {
              setColumns(columns);
            }}
          />
          {/* 失败原因分析和断点续推 */}
          <div style={{ marginTop: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Button type="primary" loading={bpLoading} onClick={handleBreakpoint}>
              断点续推
            </Button>
          </div>
        </>
      )}
    </div>
  );
};

export default ReleaseDetail;
